<template>
  <div>
    <div id="lopp" @mouseover="pauseAnimation" @mouseleave="resumeAnimation">
      <div
        v-for="(item, index) in totalData"
        :key="index"
        class="ball"
        :style="[getItemStyle(index), getBallStyle(index)]"
        @click="togglePopup(item)"
      >
        <div class="item">
          <div class="content">
            <div>{{ item.name }}</div>
            <div class="number">{{ item.number }}</div>
          </div>
          <div
            class="icon"
            :style="{
              backgroundImage: 'url(' + iconUrls[index % iconUrls.length] + ')',
            }"
          ></div>
        </div>
      </div>
    </div>

    <!-- 弹窗部分 - 修改为表格展示 -->
    <div v-if="popupVisible" class="cockpit-popup" :style="popupStyle">
      <div class="cockpit-popup-content">
        <div class="popup-header">
          <h2 class="popup-title">{{ selectedItem.name }} - 文章列表</h2>
          <button class="close-btn" @click="closePopup">×</button>
        </div>
        <div class="popup-body">
          <div class="table-container">
            <el-table
              :data="detailData"
              style="width: 100%"
              class="detail-table"
              :height="540"
              v-loading="loading"
              empty-text="暂无数据"
            >
              <el-table-column
                prop="dataName"
                label="文章标题"
                min-width="200"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <div
                    class="title-cell"
                    @click="openArticle(scope.row.dataUrl)"
                  >
                    {{ scope.row.dataName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="source"
                label="来源"
                width="120"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="dataReleaseTime"
                label="发布时间"
                width="140"
                align="center"
              >
                <template slot-scope="scope">
                  {{ formatDateTime(scope.row.dataReleaseTime) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="dataReadCount"
                label="阅读量"
                width="80"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="dataLikeCount"
                label="点赞量"
                width="80"
                align="center"
              >
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination-container" v-if="pagination.total > 0">
            <el-pagination
              small
              :current-page="pagination.currentPage"
              :page-size="pagination.size"
              :total="pagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { currentPOST } from "api/modules";
// 引入样式文件
import "@/styles/popup.scss";
import { mapState } from "vuex";

export default {
  data() {
    return {
      currentFrame: 0,
      interval: null,
      popupVisible: false,
      selectedItem: {},
      totalData: [],
      // 弹窗尺寸配置
      popupSize: {
        width: "80%",
        height: "700px",
      },
      // 详细数据
      detailData: [],
      loading: false,
      pagination: {
        currentPage: 1,
        size: 10,
        total: 0,
      },
    };
  },
  props: {
    data: {},
  },
  watch: {
    // 监听lastDay的变化，当变化时重新获取数据
    lastDay(newVal) {
      this.getData();
    },
  },
  computed: {
    ...mapState(["lastDay"]),
    iconUrls() {
      return [
        require("../../assets/img/center/center-turntable/turntable-item-dy.png"),
        require("../../assets/img/center/center-turntable/turntable-item-wxsph.png"),
        require("../../assets/img/center/center-turntable/turntable-item-wb.png"),
        require("../../assets/img/center/center-turntable/turntable-item-tt.png"),
        require("../../assets/img/center/center-turntable/turntable-item-wxgzh.png"),
      ];
    },
    // 弹窗样式计算属性
    popupStyle() {
      return {
        width: this.popupSize.width,
        height: this.popupSize.height,
        minHeight: "500px",
        maxWidth: "1200px",
        maxHeight: "700px",
      };
    },
  },
  methods: {
    getData() {
      currentPOST("centerBottomTurntablelHome", { lastDay: this.lastDay })
        .then((res) => {
          if (res.code === 0) {
            this.processTurntableData(res.data);
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("转盘数据请求失败:", error);
        });
    },

    // 处理转盘数据
    processTurntableData(apiData) {
      if (!apiData || !Array.isArray(apiData)) {
        console.warn("转盘数据格式不正确");
        return;
      }

      // 将接口数据映射为组件需要的数据格式
      this.totalData = apiData.map((item) => {
        return {
          name: item.channel, // channel -> name
          number: item.articleCount, // articleCount -> number
          source: item.source, // 保留来源信息
        };
      });
    },

    drawFrame() {
      const canvas = this.$refs.canvas;
      if (!canvas) {
        return;
      }
      const context = canvas.getContext("2d");
      const img = new Image();
      img.src = frames[this.currentFrame];
      img.onload = () => {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.drawImage(img, 0, 0, canvas.width, canvas.height);
      };

      this.currentFrame = (this.currentFrame + 1) % frames.length;
    },

    getItemStyle(index) {
      const angle = index * ((2 * Math.PI) / this.totalData.length);
      const radiusX = 350;
      const radiusY = 145;
      const gap = 20;

      const translateX = (radiusX + gap) * Math.cos(angle);
      const translateY = (radiusY + gap) * Math.sin(angle);

      return {
        transform: `translate(${translateX}px, ${translateY}px)`,
        position: "absolute",
        opacity: 1,
      };
    },

    getBallStyle(index) {
      const total = this.totalData.length;
      const durationX = 10;
      const durationY = 10;
      const durationS = 20;
      let delay = (durationS / total) * index;
      return {
        animation: `
        animX ${durationX}s cubic-bezier(0.36,0,0.64,1) -${delay}s infinite alternate,
        animY ${durationY}s cubic-bezier(0.36,0,0.64,1) -${
          delay + 5
        }s infinite alternate,
        scale ${durationS}s cubic-bezier(0.36,0,0.64,1) -${
          delay + 5
        }s infinite alternate
      `,
      };
    },

    // 设置弹窗尺寸的方法（可以在其他组件中调用）
    setPopupSize(width = "80%", height = "600px") {
      this.popupSize = { width, height };
    },

    pauseAnimation() {
      const balls = document.querySelectorAll(".ball");
      balls.forEach((ball) => {
        ball.style.animationPlayState = "paused";
      });
    },

    resumeAnimation() {
      const balls = document.querySelectorAll(".ball");
      balls.forEach((ball) => {
        ball.style.animationPlayState = "running";
      });
    },

    togglePopup(item) {
      if (this.popupVisible && this.selectedItem === item) {
        this.popupVisible = false;
        this.selectedItem = {};
      } else {
        this.popupVisible = true;
        this.selectedItem = item;
        // 打开弹窗时获取详细数据
        this.getDetailList(item);
      }
    },

    getDetailList(item) {
      this.loading = true;
      currentPOST("rightTopArticleHome", {
        lastDay: this.lastDay,
        pageSize: this.pagination.size,
        current: this.pagination.currentPage,
        channels: [item.name],
      })
        .then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.detailData = res.data.data || [];
            this.pagination.total = res.data.total || 0;
            this.pagination.currentPage = res.data.currentPage || 1;
            this.pagination.size = res.data.size || 10;
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          this.loading = false;
          console.error("详细数据请求失败:", error);
        });
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.currentPage = 1;
      this.getDetailList(this.selectedItem);
    },

    // 当前页改变
    handleCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.getDetailList(this.selectedItem);
    },

    // 打开文章链接
    openArticle(url) {
      if (url) {
        window.open(url, "_blank");
      }
    },

    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return "";

      try {
        // 处理可能的字符串格式
        let dateStr = dateTimeStr;
        if (dateStr.includes("T")) {
          dateStr = dateStr.replace("T", " ").split(".")[0];
        }

        const date = new Date(dateStr);
        if (isNaN(date.getTime())) {
          return dateTimeStr;
        }

        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");
        const hours = date.getHours().toString().padStart(2, "0");
        const minutes = date.getMinutes().toString().padStart(2, "0");

        return `${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return dateTimeStr;
      }
    },

    closePopup() {
      this.popupVisible = false;
      this.selectedItem = {};
      this.detailData = [];
      this.pagination.currentPage = 1;
    },
  },
  created() {},
  mounted() {
    this.getData();
    this.interval = setInterval(this.drawFrame, 100);
  },
  beforeDestroy() {
    clearInterval(this.interval);
  },
};
</script>

<style lang="scss" scoped>
/* --- 小球样式 --- */
.ball {
  width: 170px; /* 适度放大宽度 */
  height: 230px; /* 适度放大高度 */
  background-image: url("../../assets/img/center/center-turntable/turntable-item-bg.png");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  position: absolute;
  color: #fff;
  font-size: 25px; /* 适度放大字体 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: animation-play-state 0.5s;

  .item {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    justify-content: space-around;

    .content {
      width: 160px; /* 适度放大内容区域 */
      text-align: center;
      margin: auto;
      margin-bottom: 0;
      font-size: 21px; /* 适度放大字体 */

      .number {
        margin-top: 14px; /* 适度增加间距 */
        font-size: 23px; /* 数字字体适度放大 */
        font-weight: bold;
      }
    }

    .icon {
      width: 130px; /* 适度放大图标 */
      height: 130px; /* 适度放大图标 */
      margin: auto;
      background-size: cover;
      background-position: center;
      animation: mymove 4s infinite;
    }
  }
}

/* --- 外圈容器 --- */
#lopp {
  width: 550px; /* 适度增大容器 */
  height: 350px; /* 适度增大容器高度 */
  border-radius: 50%;
  position: absolute;
  left: -350px;
  top: -160px;
}

.popup-body {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  flex: 1;
  overflow: hidden;
}

// 标题单元格样式 - 添加省略号
.title-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  cursor: pointer;


}
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

// 分页样式
:deep(.el-pagination) {
  .btn-prev,
  .btn-next,
  .number {
    background: rgba(5, 64, 128, 0.5);
    color: #bae7ff;
    border: 1px solid #2d5278;

    &:hover {
      color: #ffffff;
      background: rgba(24, 144, 255, 0.3);
    }
  }

  .active {
    background: rgba(24, 144, 255, 0.5);
    color: #ffffff;
    border-color: #1890ff;
  }

  .el-pagination__total,
  .el-pagination__jump {
    color: #bae7ff;
  }

  .el-input__inner {
    background: rgba(5, 64, 128, 0.5);
    border: 1px solid #2d5278;
    color: #bae7ff;
  }
}
</style>

<style lang="scss">
/* --- 调整动画关键帧以适应稍大的球 --- */
@keyframes animX {
  0% {
    left: 0;
  }
  100% {
    left: 700px; /* 适度调整动画距离 */
  }
}

@keyframes animY {
  0% {
    top: 0;
  }
  100% {
    top: 350px; /* 适度调整动画距离 */
  }
}

@keyframes scale {
  0% {
    transform: scale(0.75); /* 适度调整缩放比例 */
  }
  50% {
    transform: scale(1.05); /* 适度调整缩放比例 */
  }
  100% {
    transform: scale(0.75); /* 适度调整缩放比例 */
  }
}

@keyframes mymove {
  0% {
    transform: translate(0px, -35px); /* 适度调整浮动幅度 */
  }
  50% {
    transform: translate(0px, -22px); /* 适度调整浮动幅度 */
  }
  100% {
    transform: translate(0px, -35px); /* 适度调整浮动幅度 */
  }
}
</style>
